//
//  AppDelegate.m
//  FKGW
//
//  Created by song ce on 2017/2/15.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "AppDelegate.h"
#import "TabBarControllerCongig.h"
#import "GuideViewController.h"
#import "QuickScanViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "WXApi.h"
#import <Hyphenate/Hyphenate.h>
#import "SDWebImageManager.h"
#import "IQKeyboardManager.h"
#import <AudioToolbox/AudioToolbox.h>
#import "EaseMessageViewController.h"
#import "EaseConvertToCommonEmoticonsHelper.h"
#import "EaseLocalDefine.h"
#import "OSSHelper.h"

#import "SelecedViewController.h"


#import "UMessage.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 100000
#import <UserNotifications/UserNotifications.h>
#endif

//以下几个库仅作为调试引用引用的
#import <AdSupport/AdSupport.h>
#import <CommonCrypto/CommonDigest.h>
#import <AliyunPlayerSDK/AliyunPlayerSDK.h>
#import <AMapFoundationKit/AMapFoundationKit.h>


#define IOS89 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 && [[UIDevice currentDevice].systemVersion doubleValue] < 10.0)
#define IOS10 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0)


//微信支付所需的appKey
#define  WXAPPKEY @""
//友盟推送
#define  UMAPPKEY @"58d0dada766613201e000fba"
#define UMAppMasterSecret  @"qyphajz62z0fagsjch2cxsjspkf5x1mw"
//环信聊天
#define  EMAPPKEY   @"1151170414115231#cengfengkeji"
//播放器 户权限验证
#define  AccessKeyID            @" ";
#define  AccessKeySecret   @" ";

//高德地图
#define  LocationKey  @"922dc13fec571cedf8f99a4e2276a1b5"

@interface AppDelegate ()<WXApiDelegate,EMClientDelegate,EMChatManagerDelegate,UNUserNotificationCenterDelegate,AliVcAccessKeyProtocol>

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.launchOptions = launchOptions;
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen]bounds]];

        //获取数据
    NSUserDefaults *useDefault = [NSUserDefaults standardUserDefaults];
    BOOL value = [useDefault boolForKey:@"isNext"];
    if(value==YES){//不是第一次进入
//        QuickScanViewController *quick = [[QuickScanViewController alloc]init];
//        quick.count =  1;
        SelecedViewController *quick = [[SelecedViewController alloc]init];
        self.window.rootViewController = quick;
    }else{//第一次进入 将数据写入本地
        NSUserDefaults *useDefault = [NSUserDefaults standardUserDefaults];
        [useDefault setBool:YES forKey:@"isNext"];
        //同步数据
        [useDefault synchronize];
        GuideViewController *guidVc = [[GuideViewController alloc]init];  //引导页
        self.window.rootViewController = guidVc;
    }
    //一些设置
    [self someSettings:launchOptions];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
}

-(void)regiserNoti{
    //友盟推送
    [self registerUM:self.launchOptions];
}
- (void)someSettings:(NSDictionary *)launchOptions {
    //调整弹框的时间
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(regiserNoti) name:@"regiserNoti" object:nil];
    [[SDWebImageManager sharedManager].imageDownloader setValue: nil forHTTPHeaderField:@"Accept"];
    
    //   1,注册微信支付
    //    [self registerWX];
    //   2,注册环信
    [self registerEM];
    //   3,自动登录
    [self autoLogin];
    //  4，高德地图定位
    [self registerLoactionSDK];
    //keyboard
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    [manager setShouldShowTextFieldPlaceholder:NO];
}

-(void)autoLogin{
    NSUserDefaults *useDefault = [NSUserDefaults standardUserDefaults];
    NSString *uid = [useDefault objectForKey:@"userId"];
    if(uid.length){//已经登录过
        self.uid = uid;
        [self setupUnreadMessageCount];
        DLog(@"---自动登录购物城成功---%@",_uid);
    }
}

-(void)registerLoactionSDK{
    [AMapServices sharedServices].apiKey =LocationKey;
}

-(void)registerUM:(NSDictionary *)launchOptions{
    [UMessage startWithAppkey:UMAPPKEY launchOptions:launchOptions httpsEnable:YES ];
    [UMessage openDebugMode:YES];

    //注册通知
    [UMessage registerForRemoteNotifications];
    //iOS10必须加下面这段代码。
    if (IOS10) {
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (!error) {
                DLog(@"succeeded!");
            }
            
            if (granted) {
                //点击允许
                //这里可以添加一些自己的逻辑
            } else {
                //点击不允许
                //这里可以添加一些自己的逻辑
            }
        }];
    }
    
    //这里可以添加交互式代码
    
    //打开日志，方便调试
    [UMessage setLogEnabled:YES];
}

//----------------------通知回调方法-----------------------------
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //1.2.7版本开始不需要用户再手动注册devicetoken，SDK会自动注册
    // [UMessage registerDeviceToken:deviceToken];
    DLog(@"友盟devicetoken----%@",deviceToken);
}

//ios89
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    //关闭友盟自带的弹出框
//    [UMessage setAutoAlert:NO];
    [UMessage didReceiveRemoteNotification:userInfo];
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:[NSString stringWithFormat:@"%@",userInfo] forKey:@"UMPuserInfoNotification"];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"userInfoNotification" object:self userInfo:@{@"userinfo":[NSString stringWithFormat:@"%@",userInfo]}];
}

//iOS10以下使用这个方法接收通知
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [UMessage setAutoAlert:NO];
        //应用处于前台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:[NSString stringWithFormat:@"%@",userInfo] forKey:@"UMPuserInfoNotification"];
        
    }else{
        //应用处于前台时的本地推送接受
        
        
    }
    completionHandler(UNNotificationPresentationOptionSound|UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionAlert);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:[NSString stringWithFormat:@"%@",userInfo] forKey:@"UMPuserInfoNotification"];
        
    }else{
        //应用处于后台时的本地推送接受
        
        
    }
    
}

//本地通知回调
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
  
}

//-------------------注册环信聊天--------------
-(void)registerEM {
    //AppKey:注册的AppKey，详细见下面注释。
    //apnsCertName:推送证书名（不需要加后缀），详细见下面注释。
    EMOptions *options = [EMOptions optionsWithAppkey:EMAPPKEY];
//    options.apnsCertName = @"istore_dev";
  EMError *aerr=  [[EMClient sharedClient] initializeSDKWithOptions:options];
    if(!aerr){
        DLog(@"appdelegate注册环信聊天成功");
    }else{
         DLog(@"appdelegate注册环信聊天失败--%@",aerr.errorDescription);
    }
    // 添加代理方法
    [[EMClient sharedClient] addDelegate:self delegateQueue:nil];
    //添加代理
    [[EMClient sharedClient].chatManager addDelegate:self delegateQueue:nil];
}
//环信相关代理方法
#pragma mark - EMClientDelegate

//SDK 中，如果发生自动登录，会有以下回调：
- (void)autoLoginDidCompleteWithError:(EMError *)error{
    DLog(@"环信触发自动登录行为");
}

//当掉线时，iOS SDK 会自动重连，只需要监听重连相关的回调，无需进行任何操作。
- (void)connectionStateDidChange:(EMConnectionState)aConnectionState{
    DLog(@"---环信链接状态%d",aConnectionState);
    NSString *status;
    if(aConnectionState==EMConnectionConnected){
        status = @"已连接";
    }else{
         status = @"未连接";
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"aConnectionState" object:status];
}
//当前登录账号在其它设备登录时会接收到此回调
- (void)userAccountDidLoginFromOtherDevice{
    [self logOutAction];
}
- (void)messagesDidReceive:(NSArray *)aMessages {
    
    DLog(@"用户端ap接受到了聊天消息--%@-",[aMessages.lastObject class]);
    [[NSNotificationCenter defaultCenter]postNotificationName:@"needToRefreshSessionList" object:nil];
    if(!self.isNeedToSetSixinBadge){
        [self setupUnreadMessageCount];
    }
    UIApplicationState state =[[UIApplication sharedApplication] applicationState];
    switch (state) {
            //前台运行
        case UIApplicationStateActive:
        {
            //设置消息声音提醒和本地通知；
            AudioServicesPlaySystemSound(1312);
            NSString *filePath = [[NSBundle mainBundle]pathForResource:@"in.caf" ofType:nil];
            NSURL *audioPath = [NSURL URLWithString:filePath];
            SystemSoundID sundId ;
            AudioServicesCreateSystemSoundID((__bridge CFURLRef)(audioPath), &sundId);
            //播放
            AudioServicesPlaySystemSound(sundId);
        }
            break;
            //待激活状态
        case UIApplicationStateInactive:
            break;
            //后台状态
        case UIApplicationStateBackground:
            //添加本地通知
           for (EMMessage*message in aMessages) {
               [self loadUserInfoWithMessage:message];
           }
            break;
            
        default:
            break;
            
    }
}
#pragma mark 添加本地通知
-(void)addLocalNotificationWithLastestMessage:(EMMessage*)message pre:(NSString*)pre{
    //如果已经获得发送通知的授权则创建本地通知，否则请求授权(注意：如果不请求授权在设置中是没有对应的通知设置项的，也就是说如果从来没有发送过请求，即使通过设置也打不开消息允许设置)
    if ([[UIApplication sharedApplication]currentUserNotificationSettings].types!=UIUserNotificationTypeNone) {
        //定义本地通知对象
        UILocalNotification *notification=[[UILocalNotification alloc]init];
        //ios10注册本地通知
        if (NSClassFromString(@"UNUserNotificationCenter")) {
            UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:2 repeats:NO];
            UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
            NSString *body =[self lastMessageTitle:message];
            if(pre.length){
                body = [NSString stringWithFormat:@"%@:%@",pre,body];
            }else{
                body = [NSString stringWithFormat:@"%@:%@",message.conversationId,body];
            }
            content.body = body;
//            content.userInfo = @{@"1":@"2};
            UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"iii" content:content trigger:trigger];
            [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];
        }else {//io8注册本地通知
            //设置调用时间
            notification.fireDate=[NSDate dateWithTimeIntervalSinceNow:2.0];//通知触发的时间，2s以后
            notification.repeatInterval=1;//通知重复次数
            //notification.repeatCalendar=[NSCalendar currentCalendar];//当前日历，使用前最好设置时区等信息以便能够自动同步时间
            
            //设置通知属性
            NSString *body =[self lastMessageTitle:message];
            if(pre.length){
                body = [NSString stringWithFormat:@"%@:%@",pre,body];
            }else{
                body = [NSString stringWithFormat:@"%@:%@",message.conversationId,body];
            }
            notification.alertBody=body; //通知主体
            notification.alertAction=@"打开应用"; //待机界面的滑动动作提示
            notification.alertLaunchImage=@"Default";//通过点击通知打开应用时的启动图片,这里使用程序启动图片
            notification.soundName=UILocalNotificationDefaultSoundName;//收到通知时播放的声音，默认消息声音
            //设置用户信息
            notification.userInfo=@{@"id":message.conversationId,@"user":@"Kenshin Cui"};//绑定到通知上的其他附加信息
            
            if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
                UIUserNotificationType type =  UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
                UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
                                                                                         categories:nil];
                [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
                // 通知重复提示的单位，可以是天、周、月
//                notification.repeatInterval = NSCalendarUnitDay;
            } else {
                // 通知重复提示的单位，可以是天、周、月
//                notification.repeatInterval = NSDayCalendarUnit;
            }
            //调用通知
//            [[UIApplication sharedApplication] scheduleLocalNotification:notification];
            [[UIApplication sharedApplication]presentLocalNotificationNow:notification];
        }
    }else{
        [[UIApplication sharedApplication]registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound  categories:nil]];
    }
}

// 统计未读消息数
-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[EMClient sharedClient].chatManager getAllConversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    DLog(@"未读条数---%zd",unreadCount);
    self.messageCount = unreadCount;
    [[NSNotificationCenter defaultCenter]postNotificationName:@"messageCount" object:[NSString stringWithFormat:@"%ld",unreadCount]];
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:unreadCount];
    [self setSiXinBadge:unreadCount];
}
//设置私信的未读总条数
-(void)setSiXinBadge:(NSInteger)unreadCount{
    if([self.window.rootViewController isKindOfClass:[MMDrawerController class]]){
        MMDrawerController *mm =(MMDrawerController*)self.window.rootViewController;
        CYLTabBarController *tabBar = (CYLTabBarController*)mm.centerViewController;
        UIViewController *private =tabBar.viewControllers[2];
        if(unreadCount==0){
            private.tabBarItem.badgeValue = nil;
            return;
        }
        private.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
    }
}

//-----------微信支付----支付宝支付---------------------
- (void)registerWX {
    [WXApi registerApp:WXAPPKEY withDescription:@"fengkuanggouwuchengkehuduan"];
}

#pragma mark - WXApiDelegate
//微信支付成功的回调函数
- (void) onResp:(BaseResp*)resp
{
    if([resp isKindOfClass:[PayResp class]]){
        switch (resp.errCode) {
            case WXSuccess:
                DLog(@"微信支付成功");
                //给具有微信支付功能的控制器发送通知，告诉他支付成功了，请求后台订单状态，如果也是成功的，才可以进行下一步操作
                [[NSNotificationCenter defaultCenter]postNotificationName:@"WXSuccess" object:nil userInfo:nil];
                break;
            case WXErrCodeUserCancel:
                [MBProgressHUD showInfoMessage:@"支付已取消"];
                break;
            default:
                [MBProgressHUD showInfoMessage:@"支付失败"];
                break;
        }
    }
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    if ([url.scheme isEqualToString:WXAPPKEY]){
        return  [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}
// 支付的回调
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
    //1,支付宝支付
    if ([url.host isEqualToString:@"safepay"]){
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            [[NSNotificationCenter defaultCenter]postNotificationName:@"alipayCallBack" object:nil userInfo:nil];
            int code = [[resultDic objectForKey:@"resultStatus"] intValue];
            if(code == 9000){
                 [MBProgressHUD showSuccessMessage:@"支付成功"];
            }else if (code == 8000){
                 [MBProgressHUD showInfoMessage:@"正在处理中"];
            }else if (code == 4000){
                [MBProgressHUD showInfoMessage:@"支付失败"];
            }else if (code == 6001){
                [MBProgressHUD showInfoMessage:@"支付已取消"];
            }else if (code == 6002){
                 [MBProgressHUD showInfoMessage:@"网络连接出错"];
            }
        }];
    }
    //2,微信支付
    if ([url.scheme isEqualToString:WXAPPKEY]){
        return  [WXApi handleOpenURL:url delegate:self];
    }
    return YES;
}

// NOTE: 9.0以后使用新API接口
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    //1,支付宝支付
    if ([url.host isEqualToString:@"safepay"]){
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            [[NSNotificationCenter defaultCenter]postNotificationName:@"alipayCallBack" object:nil userInfo:nil];
            int code = [[resultDic objectForKey:@"resultStatus"] intValue];
            if(code == 9000){
                [MBProgressHUD showSuccessMessage:@"支付成功"];
            }else if (code == 8000){
                [MBProgressHUD showInfoMessage:@"正在处理中"];
            }else if (code == 4000){
                [MBProgressHUD showInfoMessage:@"支付失败"];
            }else if (code == 6001){
                [MBProgressHUD showInfoMessage:@"支付已取消"];
            }else if (code == 6002){
                [MBProgressHUD showInfoMessage:@"网络连接出错"];
            }
        }];
    }
    //2,微信支付
        if ([url.scheme isEqualToString:WXAPPKEY]){
            return  [WXApi handleOpenURL:url delegate:self];
        }
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
   
}

// APP进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    self.isEnterBackground = YES;
    DLog(@"APP进入后台");
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}

// APP将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    self.isEnterBackground = NO;
    DLog(@"APP将要从后台返回");
    [[EMClient sharedClient] applicationWillEnterForeground:application];
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    [self setupUnreadMessageCount];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {

}


- (void)applicationWillTerminate:(UIApplication *)application {
  }

#pragma mark - appDelegate
+(AppDelegate *)appDealegate {
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}

#pragma mark - AliVcAccessKeyProtocol
-(AliVcAccesskey*)getAccessKeyIDSecret
{
    AliVcAccesskey* accessKey = [[AliVcAccesskey alloc] init];
    accessKey.accessKeyId = AccessKeyID;
    accessKey.accessKeySecret = AccessKeySecret;
    return accessKey;
}

- (NSString *)lastMessageTitle:(EMMessage*)lastMessage
{
    NSString *latestMessageTitle = @"";
    if (lastMessage) {
        EMMessageBody *messageBody = lastMessage.body;
        switch (messageBody.type) {
            case EMMessageBodyTypeImage:{
                latestMessageTitle = NSEaseLocalizedString(@"message.image1", @"[image]");
            } break;
            case EMMessageBodyTypeText:{
                NSString *didReceiveText = [EaseConvertToCommonEmoticonsHelper
                                            convertToSystemEmoticons:((EMTextMessageBody *)messageBody).text];
                latestMessageTitle = didReceiveText;
            } break;
            case EMMessageBodyTypeVoice:{
                latestMessageTitle = NSEaseLocalizedString(@"message.voice1", @"[voice]");
            } break;
            case EMMessageBodyTypeLocation: {
                latestMessageTitle = NSEaseLocalizedString(@"message.location1", @"[location]");
            } break;
            case EMMessageBodyTypeVideo: {
                latestMessageTitle = NSEaseLocalizedString(@"message.video1", @"[video]");
            } break;
            case EMMessageBodyTypeFile: {
                latestMessageTitle = NSEaseLocalizedString(@"message.file1", @"[file]");
            } break;
            default: {
            } break;
        }
    }
    return latestMessageTitle;
}

-(void)loadUserInfoWithMessage:(EMMessage*)message{
    NSString *userId = message.conversationId;
    if(!userId.length){
         return ;
    }
    NSDictionary  *huanxinDic =[[NSUserDefaults standardUserDefaults]objectForKey:userId];
    if(huanxinDic){
        [self addLocalNotificationWithLastestMessage:message pre:huanxinDic[@"nickName"]];
    }else{
        NSMutableArray *userNames = [NSMutableArray arrayWithObject:userId];
        NSData *pramasData = [NSJSONSerialization dataWithJSONObject:userNames options:NSJSONWritingPrettyPrinted error:nil];
        NSString *userName = [[NSString alloc]initWithData:pramasData encoding:NSUTF8StringEncoding];
        NSDictionary *paramDic = @{@"userName":userName};
        //2.68获取聊天对象信息接口
        [Tools AFNetworkingRequestTypePostWithUrl:GETCHATOBJECTSINFORMATION paramters:paramDic afterResultBlock:^(NSDictionary *resultDic) {
            DLog(@"//获取聊天对象信息接口----%@",resultDic);
            if([resultDic[@"flag"] isEqualToString:@"true"]){
                NSArray *listArr = resultDic[@"data"];
                if([listArr isKindOfClass:[NSNull class]]){
                    return ;
                }
                NSDictionary *dic = listArr.lastObject;
                NSString *nickName =dic[@"nickName"];
                dispatch_async(dispatch_get_main_queue(), ^{
                  [self addLocalNotificationWithLastestMessage:message pre:nickName];
                });
                //缓存到本地
                [[OSSHelper sharedHelper] OSSDownLoadWithObjectKey:dic[@"pic"]xOssProcess:[NSString stringWithFormat:@"image/resize,m_fill,w_%d,h_%d",48,48]  downLoadBlock:^(NSData *data) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        NSDictionary *dic = @{@"pic":data,@"nickName":nickName};
                        [[NSUserDefaults standardUserDefaults]setObject:dic forKey:userId];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        
                    });
                }];
            }
        }];
    }
}
- (void)logOutAction{
    [MBProgressHUD showTipMessageInWindow:@"退出登录成功"];
    self.uid = @"";
    NSUserDefaults *useDefault = [NSUserDefaults standardUserDefaults];
    [useDefault removeObjectForKey:@"userId"];
    [useDefault synchronize];
    [[NSNotificationCenter defaultCenter]postNotificationName:@"logOutSuccess" object:nil];
    [MBProgressHUD showTipMessageInWindow:@"您的账号在其他设备登陆了"];
}

@end
